<template>
  <view class="scan-input-container">
    <view class="scan-input-wrapper">
      <input
        ref="scanInputRef"
        v-model="inputValue"
        class="scan-input"
        type="text"
        :placeholder="placeholder"
        :disabled="!inputMethodEnabled"
        @keyup.enter="handleConfirm"
        @confirm="handleConfirm"
        autocomplete="off"
        spellcheck="false"
      />
      
      <button 
        class="scan-btn" 
        @click="handleConfirm"
        :disabled="loading"
      >
        {{ loading ? '查询中...' : '查询' }}
      </button>
    </view>

    <view class="scan-input-footer">
      <text class="scan-input-tip" v-if="tipText">{{ tipText }}</text>
      
      <view class="input-switch-container">
        <text class="switch-label">输入法{{ inputMethodEnabled ? "开启" : "关闭" }}</text>
        <view
          class="custom-switch-wrapper"
          @click="handleInputMethodSwitchChange"
        >
          <view
            class="custom-switch"
            :class="{ 'custom-switch-active': inputMethodEnabled }"
          >
            <view
              class="custom-switch-handle"
              :class="{ 'custom-switch-handle-active': inputMethodEnabled }"
            ></view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
// 导入PDA扫码功能
import { pdaScanApi } from "@/pages/smart/pdaScan";

export default {
  name: "ScanInput",
  // 混入PDA扫码功能
  mixins: [pdaScanApi],
  props: {
    // 输入框占位符
    placeholder: {
      type: String,
      default: "请输入单据"
    },
    // 提示文本
    tipText: {
      type: String,
      default: ""
    },
    // 输入值（支持v-model）
    value: {
      type: String,
      default: ""
    },
    // 加载状态
    loading: {
      type: Boolean,
      default: false
    },
    // 扫码结果处理函数
    onScanResult: {
      type: Function,
      default: null
    },
    // 确认按钮处理函数
    onConfirm: {
      type: Function,
      required: true
    }
  },
  data() {
    return {
      // 输入法开关状态
      inputMethodEnabled: true,
      // 内部输入值
      internalValue: this.value
    };
  },
  computed: {
    // 计算属性实现v-model双向绑定
    inputValue: {
      get() {
        return this.internalValue;
      },
      set(val) {
        this.internalValue = val;
        this.$emit('input', val);
      }
    }
  },
  watch: {
    // 监听外部value变化
    value: {
      handler(newVal) {
        if (newVal !== this.internalValue) {
          this.internalValue = newVal;
        }
      },
      immediate: true
    }
  },
  mounted() {
    // 初始化输入法状态
    this.initInputMethod();
    
    // 启动PDA连续扫码（如果设备支持且输入法关闭）
    if (!this.inputMethodEnabled) {
      this.startPdaContinuousScan();
    }
  },
  beforeDestroy() {
    // 停止PDA扫码
    this.stopPdaScan();
  },
  methods: {
    /**
     * 初始化输入法状态
     * 从本地存储读取保存的状态
     */
    initInputMethod() {
      const saved = uni.getStorageSync("inputMethodEnabled");
      if (saved !== null && saved !== undefined) {
        this.inputMethodEnabled = saved;
      }
    },

    /**
     * 启动PDA连续扫码
     * 在输入法关闭时启用PDA扫码
     */
    startPdaContinuousScan() {
      if (!this.inputMethodEnabled) {
        const success = this.startPdaScan((barcode) => {
          this.handleScanResult(barcode);
        });

        if (success) {
          console.log("PDA连续扫码已启动");
        } else {
          console.warn("PDA扫码启动失败，将使用手动输入模式");
        }
      }
    },

    /**
     * 处理扫码结果
     * @param {string} barcode - 扫码得到的条码内容
     */
    handleScanResult(barcode) {
      if (!barcode) return;

      console.log("PDA扫码结果:", barcode);

      // 将扫码结果赋值给输入框
      this.inputValue = barcode;

      // 如果有自定义扫码结果处理函数，先执行它
      if (this.onScanResult && typeof this.onScanResult === 'function') {
        const result = this.onScanResult(barcode);
        // 如果返回false，则不执行默认的确认操作
        if (result === false) {
          return;
        }
      }

      // 自动执行确认操作
      this.handleConfirm();
    },

    /**
     * 处理确认按钮点击或回车事件
     */
    handleConfirm() {
      if (this.loading) return;
      
      // 调用父组件传入的确认处理函数
      if (this.onConfirm && typeof this.onConfirm === 'function') {
        this.onConfirm(this.inputValue);
      }
    },

    /**
     * 输入法开关切换处理
     */
    handleInputMethodSwitchChange() {
      this.inputMethodEnabled = !this.inputMethodEnabled;

      // 保存到本地存储
      uni.setStorageSync("inputMethodEnabled", this.inputMethodEnabled);

      if (this.inputMethodEnabled) {
        // 如果开启输入法，聚焦输入框
        this.focusInput();
        // 停止PDA扫码
        this.stopPdaScan();
      } else {
        // 如果关闭输入法，启动PDA扫码
        this.startPdaContinuousScan();
      }
    },

    /**
     * 聚焦到输入框
     */
    focusInput() {
      if (this.inputMethodEnabled && this.$refs.scanInputRef) {
        this.$nextTick(() => {
          if (this.$refs.scanInputRef.focus) {
            this.$refs.scanInputRef.focus();
          }
        });
      }
    },

    /**
     * 清空输入框
     */
    clearInput() {
      this.inputValue = '';
    },

    /**
     * 设置输入框值
     */
    setValue(value) {
      this.inputValue = value;
    }
  }
};
</script>

<style lang="scss" scoped>
.scan-input-container {
  width: 100%;
}

.scan-input-wrapper {
  display: flex;
  align-items: center;
  gap: 16rpx;
  margin-bottom: 16rpx;
}

.scan-input {
  flex: 1;
  height: 70rpx;
  padding: 0 20rpx;
  border: 2rpx solid #e0e0e0;
  border-radius: 8rpx;
  font-size: 28rpx;
  background-color: #fff;
  
  &:disabled {
    background-color: #f5f5f5;
    color: #999;
  }
  
  &:focus {
    border-color: #007aff;
    outline: none;
  }
}

.scan-btn {
  height: 70rpx;
  padding: 0 30rpx;
  background-color: #007aff;
  color: white;
  border: none;
  border-radius: 8rpx;
  font-size: 28rpx;
  cursor: pointer;
  
  &:hover {
    background-color: #0056b3;
  }
  
  &:active {
    background-color: #004499;
  }
  
  &:disabled {
    background-color: #ccc;
    cursor: not-allowed;
  }
}

.scan-input-footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 8rpx;
}

.scan-input-tip {
  font-size: 24rpx;
  color: #999;
}

.input-switch-container {
  display: flex;
  align-items: center;
  gap: 16rpx;
}

.switch-label {
  font-size: 24rpx;
  color: #666;
}

.custom-switch-wrapper {
  cursor: pointer;
}

.custom-switch {
  width: 100rpx;
  height: 50rpx;
  background-color: #ccc;
  border-radius: 25rpx;
  position: relative;
  transition: background-color 0.3s;
}

.custom-switch-active {
  background-color: #007aff;
}

.custom-switch-handle {
  width: 46rpx;
  height: 46rpx;
  background-color: white;
  border-radius: 50%;
  position: absolute;
  top: 2rpx;
  left: 2rpx;
  transition: transform 0.3s;
  box-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.2);
}

.custom-switch-handle-active {
  transform: translateX(50rpx);
}
</style>